<?php

namespace Home\Service;

/**
 * 用户业务
 */
class User {
	private $_daoUserModel;
	private $_daoReqModel;
	private $_svrVxModel;

	/**
	 * 构造函数
	 * @param  void
	 * @return void
	 */
	public function __construct() {
		$this->_daoUserModel = \Lsf\Loader::Model('DaoUser', TRUE);
		$this->_daoReqModel = \Lsf\Loader::Model('DaoRequestNum', TRUE);
		$this->_svrVxModel = \Lsf\Loader::Model('SvrWeixin', TRUE);
	}

	/**
	 * 添加会员信息
	 */
	public function addUser($openId, $userName, $phone, $companyName, $employeeNum) {
		// 先查询
		$user =  $this->_daoUserModel->select('user_id,phone,company_name,employee_num', ['open_id' => $openId], 'user_id ASC', 1, FALSE);
		if($user === FALSE){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
			]);
			return FALSE;
		}
		if(empty($user)) {
			$newUser = [
				'user_name'    => $userName,
				'phone'        => $phone,
				'company_name' => $companyName,
				'employee_num' => $employeeNum,
				'status'       => 1,
				'create_time'  => date("Y-m-d H:i:s",time()),
				'open_id'      => $openId,
				'point'        => 0
			];
			$userId = $this->_daoUserModel->insert($newUser);
			if ($userId === FALSE) {
				\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
					'model_name' => 'dao_user',
					'insert'     => $newUser
				]);
				return FALSE;
			}
		}else{
			$userId = $user[0]['user_id'];
		}
		$result= [
			'uid' => $userId,
		];
		return $result;
	}

	/**
	 * 修改会员信息
	 */
	public function editUser($uid, $userName, $phone, $companyName, $employeeNum) {
		$userList =  $this->_daoUserModel->select('user_id,user_name,phone,company_name,employee_num', ['user_id' => $uid], 'user_id ASC', 1, FALSE);
		if($userList === FALSE || empty($userList)){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'select_result' => $userList,
			]);
			return FALSE;
		}
		$user = [];
		if(!empty($userName) && $userList[0]['user_name'] != $userName ){
			$user['user_name'] = $userName;
		}
		if(!empty($phone) && $userList[0]['phone'] != $phone){
			$user['phone'] = $phone;
		}
		if(!empty($companyName) && $userList[0]['company_name'] != $companyName){
			$user['company_name'] = $companyName;
		}
		if(!empty($employeeNum) && $userList[0]['employee_num'] != $employeeNum){
			$user['employee_num'] = $employeeNum;
		}
		if(empty($user)){
			return $result = [
				'uid' => $uid,
			];
		}
		$where = [
			'user_id' => $uid
		];
		$rows = $this->_daoUserModel->update($user, $where);
		if($rows !== 1){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'update'     => $user,
				'where'      => $where,
			]);
			return FALSE;
		}
		$result = [
			'uid' => $uid,
		];
		return $result;
	}

	/**
	 * 获取会员信息
	 */
	public function getUser($uid, $phone) {
		$where = [];
		if(!empty($uid)) {
			$where['user_id'] = $uid;
		}
		if(!empty($phone)) {
			$where['phone'] = $phone;
		}
		if(empty($where)){
			return -1;
		}
		$user =  $this->_daoUserModel->select('*', $where, 'user_id ASC', 1, FALSE);
		if($user === FALSE){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'select_result' => $user
			]);
			return FALSE;
		}
		if(empty($user)){
			return -1;
		}
		return $user[0];
	}

	/**
	 * 提交明信片url
	 */
	public function addCardUrl($uid, $url) {
		$userList =  $this->_daoUserModel->select('user_id,card_url', ['user_id' => $uid], 'user_id ASC', 1, FALSE);
		if($userList === FALSE || empty($userList)){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'select_result' => $userList,
			]);
			return FALSE;
		}
		if($userList[0]['card_url'] == $url){
			return ['uid' => $userList[0]['user_id']];
		}
		// 需要修改则修改
		$user = [
			'card_url' => $url
		];
		$where = [
			'user_id' => $uid
		];
		$rows = $this->_daoUserModel->update($user, $where);
		if($rows !== 1){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
				'update'     => $user,
				'where'      => $where,
			]);
			return FALSE;
		}
		$result[] = [
			'uid' => $uid,
		];
		return $result;
	}

	/**
	 * 获取微信用户信息
	 */
	public function getWxUserInfo($VXCode){
		$result = $this->_svrVxModel->getVxAccessToken($VXCode);
		if(is_array($result)){
			if(isset($result['errcode'])){
				\Lsf\Loader::plugin('Log')->error(SVR_FAIL, [
					'model_name' => 'svr_weixin',
					'result' => $result,
				]);
				return FALSE;
			}else{
				// 访问量增加
				$this->addRequestNum();
				// 查询是否已经注册
				$userList =  $this->_daoUserModel->select('user_id', ['open_id' => $result['openid']], 'user_id ASC', 1, FALSE);
				if(is_array($userList) && !empty($userList)){
					return [
						'open_id' => $result['openid'],
						'uid'     => $userList[0]['user_id']
					];
				}else {
					return [
						'open_id' => $result['openid'],
						'uid'     => 0
					];
				}
			}
		}else{
			\Lsf\Loader::plugin('Log')->error(SVR_FAIL, [
				'model_name' => 'svr_weixin',
				'result' => $result,
			]);
			return FALSE;
		}
	}

	/**
	 * 获取用户列表
	 */
	public function getUserList($userName, $phone, $pageSize, $pageNo){
		$where = [];
		if(!empty($userName)) {
			$where['user_name'] = $userName;
		}
		if(!empty($phone)) {
			$where['phone'] = $phone;
		}
		$limit = ($pageNo - 1) * $pageSize;
		$user =  $this->_daoUserModel->select('user_id,phone,company_name,employee_num,user_name,point', $where, 'user_id DESC', $limit . ',' . $pageSize, FALSE);
		if($user === FALSE){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
			]);
			return FALSE;
		}
		$list = [];
		foreach ($user as $item){
			$list[] = $item;
		}
		$count = $this->_daoUserModel->count('user_id', $where);
		if(!is_int($count)){
			return FALSE;
		}
		$totalPage = intval($count / $pageSize);
		if($count % $pageSize > 0){
			$totalPage++;
		}
		return [
			'list' => $list,
			'page_no' => intval($pageNo),
			'page_size' => intval($pageSize),
			'total_page' => $totalPage,
			'total_num' => $count,
		];
	}

	/**
	 * 增加访问量
	 */
	private function addRequestNum(){
		$date = date("Y-m-d",time());
		$req =  $this->_daoReqModel->select('id,date,num', ['date' => $date], 'id ASC', 1, FALSE);
		if(empty($req)){
			$newDate = [
				'date'    	   => $date,
				'num'          => 1,
				'create_time'  => date("Y-m-d H:i:s",time()),
			];
			$reqId = $this->_daoReqModel->insert($newDate);
			// 成功则返回，失败则查询并增量
			if (is_int($reqId) && $reqId > 0) {
				return 1;
			}else{
				$req =  $this->_daoReqModel->select('id,date,num', ['date' => $date], 'id ASC', 1, FALSE);
				if(empty($req)){
					\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
						'model_name' => 'dao_request_num',
						'desc' => '插入失败后，查询失败'
					]);
				}
			}
		}
		// 需要修改则修改
		$up = [
			'num' => $req[0]['num'] + 1
		];
		$where = [
			'id' => $req[0]['id']
		];
		$rows = $this->_daoReqModel->update($up, $where);
		if($rows !== 1){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_request_num',
				'update'     => $up,
				'where'      => $where,
			]);
			return 1;
		}
		return 1;
	}

	/**
	 * 排行
	 */
	public function getRankList(){
		$where = [];
		if(!empty($userName)) {
			$where['user_name'] = $userName;
		}
		if(!empty($phone)) {
			$where['phone'] = $phone;
		}
		$where['point'] = ['gt', 0];
		//$limit = ($pageNo - 1) * $pageSize;
		$user =  $this->_daoUserModel->select('user_id,company_name,user_name,point', $where, 'point DESC', 20, FALSE);
		if($user === FALSE){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_user',
			]);
			return FALSE;
		}
		return ['list' => $user];
	}

	/**
	 * 访问量
	 */
	public function getReqNum(){
		$nowDate = date("Y-m-d",time());
		$now =  $this->_daoReqModel->select('id,num', ['date' => $nowDate], 'id ASC', 1, FALSE);
		if(empty($now)){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_request_num',
				'desc' => '访问量柱状图查询失败'
			]);
		}
		$nowNum = $now[0]['num'];

		$monthDate = date("Y-m-d",time() - 60 * 60 * 24 * 30);
		$month =  $this->_daoReqModel->select('id,num', ['date' => [ 'egt' , $monthDate]], 'id ASC', 31, FALSE);
		if(empty($month)){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_request_num',
				'desc' => '访问量柱状图查询失败'
			]);
		}
		$monthNum = 0;
		foreach ($month as $item){
			$monthNum += $item['num'];
		}

		$yearDate = date("Y-m-d",time() - 60 * 60 * 24 * 365);
		$year =  $this->_daoReqModel->select('id,num', ['date' => [ 'egt' , $yearDate]], 'id ASC', 365, FALSE);
		if(empty($year)){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_request_num',
				'desc' => '访问量柱状图查询失败'
			]);
		}
		$yearNum = 0;
		foreach ($year as $item){
			$yearNum += $item['num'];
		}

		$all =  $this->_daoReqModel->select('id,num', ['date' => [ 'egt' , 0]], 'id ASC', 999, FALSE);
		if(empty($all)){
			\Lsf\Loader::plugin('Log')->error(DATABASE_OPERATE_FAIL, [
				'model_name' => 'dao_request_num',
				'desc' => '访问量柱状图查询失败'
			]);
		}
		$allNum = 0;
		foreach ($all as $item){
			$allNum += $item['num'];
		}
		return [
			'total' => $allNum,
			'list' => [
				[
					'name' => '今天',
					'num' => $nowNum
				],
				[
					'name' => '近一个月',
					'num' => $monthNum
				],
				[
					'name' => '近一年',
					'num' => $yearNum
				]
			]
		];

	}
}